﻿using CRM.Models;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using CRM.Services.Customer;

namespace CRM.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LabelController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly CustomerService _service;
        private readonly UserManager<User> _userManager;

        public LabelController(MyDbContext dbContext, UserManager<User> userManager, CustomerService service)
        {
            _dbContext = dbContext;
            _userManager = userManager;
            _service = service;
        }

        [HttpGet(nameof(List))]
        public async Task<ResultStruct> List([FromQuery] CustomerLabel label, [FromQuery] int page = 1, [FromQuery] int limit = 20)
        {
            var Model = _service.LabelCondition();

            if (!string.IsNullOrEmpty(label.Name))
            {
                Model = Model.Where(m => m.Name == label.Name);
            }
            var List = await Model.Include(m => m.User).OrderByDescending(m => m.Id).ToPaginateAsync(page, limit);
            return Success(List);
        }

        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(CustomerLabel label)
        {
            var user = await _userManager.GetUserAsync(User);

            var Model = _service.LabelCondition();
            //去重
            var repeat = await Model.Where(m => m.Name == label.Name).FirstOrDefaultAsync();

            if (repeat != null)
            {
                return Error(new object(), "标签已存在");
            }

            var Time = DateTime.Now;
            label.UpdatedAt = Time;
            label.CreatedAt = Time;
            label.UserId = user.Id;
            label.OemId = user.OemId;
            label.CompanyId = user.CompanyId;
            label.GroupId = user.GroupId;
            _dbContext.CustomerLabel.Add(label);
            var status = await _dbContext.SaveChangesAsync();
            if (status == 1)
            {
                return Success(new object(), "创建成功");

            }
            return Error(new object(), "创建失败");
        }

        [HttpGet("{id}")]
        public async Task<ResultStruct> Get(int id)
        {
            var Model = _service.LabelCondition();

            var row = await _dbContext.CustomerLabel.Where(m => m.Id == id).FirstOrDefaultAsync();

            return row == null ? Error(new object(), "获取失败") : Success(row, "获取成功");
        }


        [HttpPut("{id}")]
        public async Task<ResultStruct> Update(CustomerLabel label)
        {
            if (label.Id <= 0)
            {
                return Error(new object(), "参数错误");
            }


            var Model = _service.LabelCondition();

            var row = await Model.Where(m => m.Id == label.Id).FirstOrDefaultAsync();

            if (row == null)
            {
                return Error(new object(), "数据不存在");
            }

            //去重
            var repeat = await Model.Where(m => m.Name == label.Name && m.Id != label.Id).FirstOrDefaultAsync();

            if (repeat != null)
            {
                return Error(new object(), "标签已存在");
            }

            var Time = DateTime.Now;
            row.UpdatedAt = Time;
            row.Name = label.Name;
            row.Color = label.Color;
            var status = await _dbContext.SaveChangesAsync();
            if (status == 1)
            {
                return Success(new object(), "更新成功");

            }
            return Error(new object(), "更新失败");
        }

        [HttpDelete("{id}")]
        public async Task<ResultStruct> Delete(int id)
        {
            var Model = _service.LabelCondition();

            var row = await _dbContext.CustomerLabel.Where(m => m.Id == id).FirstOrDefaultAsync();

            if (row == null)
            {
                return Error(new object(), "数据不存在");
            }

            _dbContext.Remove(row);
            var status = await _dbContext.SaveChangesAsync();

            if (status > 0)
            {
                return Success(new object(), "删除成功");

            }
            return Error(new object(), "删除失败");
        }

        [HttpDelete(nameof(DeleteCollect))]
        public async Task<ResultStruct> DeleteCollect(List<int> ids)
        {
            var Model = _service.LabelCondition();

            var row = await _dbContext.CustomerLabel.Where(m => ids.Contains(m.Id)).ToListAsync();

            if (row.Count <= 0)
            {
                return Error(new object(), "数据不存在");
            }

            _dbContext.RemoveRange(row);
            var status = await _dbContext.SaveChangesAsync();

            if (status > 0)
            {
                return Success(new object(), "删除成功");

            }
            return Error(new object(), "删除失败");
        }

        [HttpGet(nameof(Collect))]
        public async Task<ResultStruct> Collect()
        {
            var Model = _service.LabelCondition();

            var List = await _dbContext.CustomerLabel.OrderByDescending(m => m.Id).Select(item => new { item.Id, item.Name }).ToListAsync();

            return Success(List);
        }

    }
}
